<template>
  <div class="execution-status" :class="{ 'dark': isDark }">
    <!-- 执行总览 -->
    <div class="execution-overview">
      <div class="status-header">
        <div class="status-info">
          <h3 class="status-title">执行状态</h3>
          <el-tag 
            :type="statusTagType" 
            :effect="statusEffect"
            size="large"
          >
            {{ statusText }}
          </el-tag>
        </div>
        <div class="status-actions">
          <el-button
            v-if="canPause"
            :icon="VideoPause"
            type="warning"
            size="small"
            @click="handlePause"
          >
            暂停
          </el-button>
          <el-button
            v-if="canResume"
            :icon="VideoPlay"
            type="primary"
            size="small"
            @click="handleResume"
          >
            继续
          </el-button>
          <el-button
            v-if="canCancel"
            :icon="Close"
            type="danger"
            size="small"
            @click="handleCancel"
          >
            取消
          </el-button>
        </div>
      </div>

      <!-- 整体进度 -->
      <div class="overall-progress">
        <div class="progress-info">
          <span class="progress-label">整体进度</span>
          <span class="progress-text">
            {{ executionStatus.progress.completed }}/{{ executionStatus.progress.total }} 任务
            ({{ Math.round(executionStatus.progress.overall) }}%)
          </span>
        </div>
        <el-progress
          :percentage="executionStatus.progress.overall"
          :status="progressStatus"
          :stroke-width="8"
          :show-text="false"
        />
      </div>

      <!-- 时间信息 -->
      <div class="timing-info">
        <div class="timing-item">
          <el-icon><Clock /></el-icon>
          <span class="timing-label">已用时间:</span>
          <span class="timing-value">{{ formatDuration(elapsedTime) }}</span>
        </div>
        <div class="timing-item" v-if="estimatedRemaining > 0">
          <el-icon><Timer /></el-icon>
          <span class="timing-label">预计剩余:</span>
          <span class="timing-value">{{ formatDuration(estimatedRemaining) }}</span>
        </div>
      </div>
    </div>

    <!-- 当前执行任务 -->
    <div class="current-task" v-if="currentTask">
      <h4 class="current-task-title">当前任务</h4>
      <div class="current-task-content">
        <div class="task-info">
          <span class="task-name">{{ currentTask.description }}</span>
          <el-tag size="small" :type="getTaskTypeColor(currentTask.type)">
            {{ getTaskTypeName(currentTask.type) }}
          </el-tag>
        </div>
        <el-progress
          :percentage="currentTask.progress"
          :stroke-width="6"
          :show-text="true"
        />
      </div>
    </div>

    <!-- 选项卡 -->
    <el-tabs v-model="activeTab" class="execution-tabs">
      <!-- 时间线视图 -->
      <el-tab-pane label="执行时间线" name="timeline">
        <div class="timeline-container">
          <el-timeline>
            <el-timeline-item
              v-for="item in timelineItems"
              :key="item.id"
              :timestamp="item.timestamp"
              :type="item.type"
              :color="item.color"
              :icon="item.icon"
              :size="item.size"
            >
              <div class="timeline-content">
                <h4 class="timeline-title">{{ item.title }}</h4>
                <p class="timeline-description" v-if="item.description">
                  {{ item.description }}
                </p>
                <div class="timeline-metadata" v-if="item.metadata">
                  <el-tag
                    v-for="(value, key) in item.metadata"
                    :key="key"
                    size="small"
                    effect="plain"
                  >
                    {{ key }}: {{ value }}
                  </el-tag>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-tab-pane>

      <!-- 日志视图 -->
      <el-tab-pane label="执行日志" name="logs">
        <div class="logs-container">
          <div class="logs-toolbar">
            <el-select
              v-model="logLevelFilter"
              placeholder="日志级别"
              size="small"
              style="width: 120px"
              @change="filterLogs"
            >
              <el-option label="全部" value="ALL" />
              <el-option label="信息" value="INFO" />
              <el-option label="警告" value="WARNING" />
              <el-option label="错误" value="ERROR" />
            </el-select>
            <el-button
              :icon="Refresh"
              size="small"
              @click="refreshLogs"
            >
              刷新
            </el-button>
            <el-button
              :icon="Download"
              size="small"
              @click="downloadLogs"
            >
              导出
            </el-button>
          </div>
          <div class="logs-content" ref="logsContainer">
            <div
              v-for="log in filteredLogs"
              :key="log.id"
              class="log-entry"
              :class="`log-${log.level.toLowerCase()}`"
            >
              <span class="log-timestamp">{{ formatLogTime(log.timestamp) }}</span>
              <el-tag
                :type="getLogLevelType(log.level)"
                size="small"
                effect="plain"
              >
                {{ log.level }}
              </el-tag>
              <span class="log-task" v-if="log.taskId">
                [{{ getTaskName(log.taskId) }}]
              </span>
              <span class="log-message">{{ log.message }}</span>
              <div class="log-details" v-if="log.details && Object.keys(log.details).length > 0">
                <pre>{{ JSON.stringify(log.details, null, 2) }}</pre>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- 资源监控 -->
      <el-tab-pane label="资源监控" name="resources">
        <div class="resources-container">
          <div class="resource-cards">
            <div class="resource-card">
              <div class="resource-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="resource-info">
                <h4>智能体使用</h4>
                <span class="resource-value">
                  {{ executionStatus.resources.agentsUsed }}
                </span>
              </div>
            </div>
            <div class="resource-card">
              <div class="resource-icon">
                <el-icon><Connection /></el-icon>
              </div>
              <div class="resource-info">
                <h4>MCP服务调用</h4>
                <span class="resource-value">
                  {{ executionStatus.resources.mcpServicesCalled }}
                </span>
              </div>
            </div>
            <div class="resource-card">
              <div class="resource-icon">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="resource-info">
                <h4>内存使用</h4>
                <span class="resource-value">
                  {{ executionStatus.resources.memoryUsage }}MB
                </span>
              </div>
            </div>
            <div class="resource-card">
              <div class="resource-icon">
                <el-icon><Cpu /></el-icon>
              </div>
              <div class="resource-info">
                <h4>CPU使用率</h4>
                <span class="resource-value">
                  {{ Math.round(executionStatus.resources.cpuUsage) }}%
                </span>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useTaskStore } from '@/stores/task'
import { useUIStore } from '@/stores/ui'
import {
  VideoPause,
  VideoPlay,
  Close,
  Clock,
  Timer,
  Refresh,
  Download,
  User,
  Connection,
  Monitor,
  Cpu
} from '@element-plus/icons-vue'
import type { ExecutionStatus, ExecutionLog, Task, TimelineItem } from '@/types'

// Stores
const taskStore = useTaskStore()
const uiStore = useUIStore()
const { isDark } = storeToRefs(uiStore)

// Props
interface Props {
  sessionId: string
}

const props = defineProps<Props>()

// 响应式数据
const activeTab = ref('timeline')
const logLevelFilter = ref('ALL')
const logsContainer = ref<HTMLElement>()

// 计算属性
const executionStatus = computed(() => taskStore.executionStatus)
const currentTask = computed(() => taskStore.currentTask)
const allLogs = computed(() => executionStatus.value?.logs || [])

const statusText = computed(() => {
  const status = executionStatus.value?.status
  const statusMap = {
    QUEUED: '队列中',
    RUNNING: '执行中',
    COMPLETED: '已完成',
    FAILED: '执行失败',
    TIMEOUT: '执行超时',
    CANCELLED: '已取消'
  }
  return statusMap[status] || '未知状态'
})

const statusTagType = computed(() => {
  const status = executionStatus.value?.status
  const typeMap = {
    QUEUED: 'info',
    RUNNING: 'primary',
    COMPLETED: 'success',
    FAILED: 'danger',
    TIMEOUT: 'warning',
    CANCELLED: 'info'
  }
  return typeMap[status] || 'info'
})

const statusEffect = computed(() => {
  const status = executionStatus.value?.status
  return status === 'RUNNING' ? 'light' : 'plain'
})

const progressStatus = computed(() => {
  const status = executionStatus.value?.status
  if (status === 'FAILED') return 'exception'
  if (status === 'COMPLETED') return 'success'
  return undefined
})

const canPause = computed(() => executionStatus.value?.status === 'RUNNING')
const canResume = computed(() => executionStatus.value?.status === 'PAUSED')
const canCancel = computed(() => ['QUEUED', 'RUNNING', 'PAUSED'].includes(executionStatus.value?.status))

const elapsedTime = computed(() => {
  if (!executionStatus.value?.timing.startTime) return 0
  const start = new Date(executionStatus.value.timing.startTime).getTime()
  const end = executionStatus.value.timing.actualEndTime
    ? new Date(executionStatus.value.timing.actualEndTime).getTime()
    : Date.now()
  return Math.max(0, end - start)
})

const estimatedRemaining = computed(() => {
  if (!executionStatus.value?.timing.estimatedEndTime) return 0
  const end = new Date(executionStatus.value.timing.estimatedEndTime).getTime()
  const now = Date.now()
  return Math.max(0, end - now)
})

const timelineItems = computed(() => {
  const items: TimelineItem[] = []
  
  // 添加开始执行事件
  if (executionStatus.value?.timing.startTime) {
    items.push({
      id: 'start',
      title: '开始执行',
      timestamp: formatTime(executionStatus.value.timing.startTime),
      type: 'primary',
      size: 'large',
      icon: VideoPlay
    })
  }

  // 添加任务完成事件
  const tasks = taskStore.tasks
  tasks.forEach(task => {
    if (task.status === 'COMPLETED' && task.completedAt) {
      items.push({
        id: task.id,
        title: `任务完成: ${task.description}`,
        description: `执行时间: ${task.actualTime}s`,
        timestamp: formatTime(task.completedAt),
        type: 'success',
        metadata: {
          '任务类型': getTaskTypeName(task.type),
          '置信度': task.result?.confidence ? `${Math.round(task.result.confidence * 100)}%` : 'N/A'
        }
      })
    } else if (task.status === 'FAILED') {
      items.push({
        id: task.id,
        title: `任务失败: ${task.description}`,
        description: task.error?.message,
        timestamp: formatTime(task.updatedAt),
        type: 'danger',
        color: '#F56C6C'
      })
    }
  })

  // 添加结束执行事件
  if (executionStatus.value?.timing.actualEndTime) {
    items.push({
      id: 'end',
      title: statusText.value,
      timestamp: formatTime(executionStatus.value.timing.actualEndTime),
      type: executionStatus.value.status === 'COMPLETED' ? 'success' : 'danger',
      size: 'large'
    })
  }

  return items.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime())
})

const filteredLogs = computed(() => {
  if (logLevelFilter.value === 'ALL') {
    return allLogs.value
  }
  return allLogs.value.filter(log => log.level === logLevelFilter.value)
})

// 方法
const formatDuration = (ms: number): string => {
  const seconds = Math.floor(ms / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  
  if (hours > 0) {
    return `${hours}h ${minutes % 60}m ${seconds % 60}s`
  } else if (minutes > 0) {
    return `${minutes}m ${seconds % 60}s`
  } else {
    return `${seconds}s`
  }
}

const formatTime = (timestamp: string): string => {
  return new Date(timestamp).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const formatLogTime = (timestamp: string): string => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    fractionalSecondDigits: 3
  })
}

const getTaskTypeName = (type: string): string => {
  const typeMap = {
    RESEARCH: '研究分析',
    ANALYSIS: '数据分析',
    CALCULATION: '计算处理',
    REASONING: '逻辑推理',
    SYNTHESIS: '综合整理'
  }
  return typeMap[type] || type
}

const getTaskTypeColor = (type: string): string => {
  const colorMap = {
    RESEARCH: 'primary',
    ANALYSIS: 'success',
    CALCULATION: 'warning',
    REASONING: 'danger',
    SYNTHESIS: 'info'
  }
  return colorMap[type] || 'info'
}

const getLogLevelType = (level: string): string => {
  const typeMap = {
    INFO: 'info',
    WARNING: 'warning',
    ERROR: 'danger'
  }
  return typeMap[level] || 'info'
}

const getTaskName = (taskId: string): string => {
  const task = taskStore.tasks.find(t => t.id === taskId)
  return task ? task.description.substring(0, 20) + '...' : taskId
}

const handlePause = () => {
  taskStore.pauseExecution(props.sessionId)
}

const handleResume = () => {
  taskStore.resumeExecution(props.sessionId)
}

const handleCancel = () => {
  taskStore.cancelExecution(props.sessionId)
}

const filterLogs = () => {
  // 过滤逻辑已在计算属性中实现
}

const refreshLogs = () => {
  taskStore.fetchExecutionLogs(props.sessionId)
}

const downloadLogs = () => {
  const logsText = allLogs.value
    .map(log => `${formatLogTime(log.timestamp)} [${log.level}] ${log.message}`)
    .join('\n')
  
  const blob = new Blob([logsText], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `execution-logs-${props.sessionId}-${Date.now()}.txt`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 监听日志变化，自动滚动到底部
watch(
  () => allLogs.value.length,
  () => {
    if (activeTab.value === 'logs' && logsContainer.value) {
      setTimeout(() => {
        logsContainer.value!.scrollTop = logsContainer.value!.scrollHeight
      }, 100)
    }
  }
)

// 生命周期
onMounted(() => {
  // 开始监听执行状态
  taskStore.startExecutionStatusMonitoring(props.sessionId)
})

onUnmounted(() => {
  // 停止监听执行状态
  taskStore.stopExecutionStatusMonitoring()
})
</script>

<style scoped lang="scss">
.execution-status {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);
  border-radius: 8px;
  overflow: hidden;

  &.dark {
    background: var(--el-bg-color-darker);
  }
}

.execution-overview {
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color);
  
  .status-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .status-info {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .status-title {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }
    
    .status-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .overall-progress {
    margin-bottom: 16px;
    
    .progress-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      .progress-label {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
      
      .progress-text {
        font-size: 14px;
        color: var(--el-text-color-regular);
      }
    }
  }
  
  .timing-info {
    display: flex;
    gap: 24px;
    
    .timing-item {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 14px;
      
      .timing-label {
        color: var(--el-text-color-regular);
      }
      
      .timing-value {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
    }
  }
}

.current-task {
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color);
  
  .current-task-title {
    margin: 0 0 12px 0;
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
  
  .current-task-content {
    .task-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      .task-name {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
    }
  }
}

.execution-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  :deep(.el-tabs__content) {
    flex: 1;
    padding: 0;
  }
  
  :deep(.el-tab-pane) {
    height: 100%;
  }
}

.timeline-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .timeline-content {
    .timeline-title {
      margin: 0 0 8px 0;
      font-size: 14px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }
    
    .timeline-description {
      margin: 0 0 8px 0;
      font-size: 13px;
      color: var(--el-text-color-regular);
    }
    
    .timeline-metadata {
      display: flex;
      gap: 6px;
      flex-wrap: wrap;
    }
  }
}

.logs-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .logs-toolbar {
    padding: 12px 20px;
    border-bottom: 1px solid var(--el-border-color);
    display: flex;
    gap: 8px;
    align-items: center;
  }
  
  .logs-content {
    flex: 1;
    padding: 12px 20px;
    overflow-y: auto;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 12px;
    line-height: 1.5;
    
    .log-entry {
      display: flex;
      align-items: flex-start;
      gap: 8px;
      padding: 4px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      &:last-child {
        border-bottom: none;
      }
      
      .log-timestamp {
        flex-shrink: 0;
        color: var(--el-text-color-placeholder);
        font-size: 11px;
      }
      
      .log-task {
        flex-shrink: 0;
        color: var(--el-color-primary);
        font-weight: 500;
      }
      
      .log-message {
        flex: 1;
        color: var(--el-text-color-primary);
      }
      
      .log-details {
        margin-top: 4px;
        padding: 8px;
        background: var(--el-bg-color-page);
        border-radius: 4px;
        
        pre {
          margin: 0;
          font-size: 11px;
          color: var(--el-text-color-regular);
        }
      }
      
      &.log-warning {
        background: rgba(245, 108, 108, 0.05);
      }
      
      &.log-error {
        background: rgba(245, 108, 108, 0.1);
      }
    }
  }
}

.resources-container {
  padding: 20px;
  
  .resource-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    
    .resource-card {
      padding: 20px;
      background: var(--el-bg-color-overlay);
      border: 1px solid var(--el-border-color);
      border-radius: 8px;
      display: flex;
      align-items: center;
      gap: 16px;
      
      .resource-icon {
        width: 48px;
        height: 48px;
        background: var(--el-color-primary-light-8);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--el-color-primary);
        font-size: 24px;
      }
      
      .resource-info {
        flex: 1;
        
        h4 {
          margin: 0 0 8px 0;
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
        
        .resource-value {
          font-size: 24px;
          font-weight: 600;
          color: var(--el-text-color-primary);
        }
      }
    }
  }
}
</style>